package com.facetoface;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.bridge.ReadableMap;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import android.util.Log;

public class WeChatManager extends ReactContextBaseJavaModule {
    
    private static final String TAG = "WeChatManager";
    private static String appId;
    private static IWXAPI api;
    private static Promise loginPromise;
    private static Promise payPromise;
    
    public WeChatManager(ReactApplicationContext reactContext) {
        super(reactContext);
    }
    
    @Override
    public String getName() {
        return "WeChatManager";
    }
    
    /**
     * 获取当前应用ID
     * @return appId
     */
    public static String getAppId() {
        return appId;
    }
    
    /**
     * 处理微信登录和分享回调
     * @param resp 微信回调响应
     */
    public static void handleResponse(BaseResp resp) {
        if (loginPromise != null) {
            WritableMap result = new WritableNativeMap();
            result.putInt("errCode", resp.errCode);
            result.putString("errStr", resp.errStr);
            result.putString("openId", resp.openId);
            
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    // 登录成功
                    loginPromise.resolve(result);
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    // 用户取消
                    loginPromise.reject("ERR_USER_CANCEL", "用户取消登录");
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    // 用户拒绝授权
                    loginPromise.reject("ERR_AUTH_DENIED", "用户拒绝授权");
                    break;
                default:
                    // 其他错误
                    loginPromise.reject("ERR_WECHAT", "微信登录失败");
                    break;
            }
            
            loginPromise = null;
        }
    }
    
    /**
     * 处理微信支付回调
     * @param resp 微信支付回调响应
     */
    public static void handlePayResponse(BaseResp resp) {
        if (payPromise != null) {
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    // 支付成功
                    payPromise.resolve("支付成功");
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    // 用户取消支付
                    payPromise.reject("ERR_USER_CANCEL", "用户取消支付");
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    // 用户拒绝支付
                    payPromise.reject("ERR_AUTH_DENIED", "用户拒绝支付");
                    break;
                default:
                    // 支付失败
                    payPromise.reject("ERR_WECHAT_PAY", "微信支付失败");
                    break;
            }
            
            payPromise = null;
        }
    }
    
    /**
     * 注册微信应用
     * @param appId 微信应用ID
     * @param promise Promise回调
     */
    @ReactMethod
    public void registerApp(String appId, Promise promise) {
        try {
            WeChatManager.appId = appId;
            api = WXAPIFactory.createWXAPI(getReactApplicationContext(), appId, true);
            boolean result = api.registerApp(appId);
            promise.resolve(result);
        } catch (Exception e) {
            promise.reject("REGISTER_APP_ERROR", e.getMessage());
        }
    }
    
    /**
     * 微信登录
     * @param appId 微信应用ID
     * @param promise Promise回调
     */
    @ReactMethod
    public void login(String appId, Promise promise) {
        try {
            if (api == null) {
                promise.reject("NOT_REGISTERED", "请先注册微信应用");
                return;
            }
            
            if (!api.isWXAppInstalled()) {
                promise.reject("NOT_INSTALLED", "未安装微信");
                return;
            }
            
            loginPromise = promise;
            
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "face_to_face_auth";
            api.sendReq(req);
        } catch (Exception e) {
            promise.reject("LOGIN_ERROR", e.getMessage());
        }
    }
    
    /**
     * 微信支付
     * @param payload 支付参数
     * @param promise Promise回调
     */
    @ReactMethod
    public void pay(ReadableMap payload, Promise promise) {
        try {
            if (api == null) {
                promise.reject("NOT_REGISTERED", "请先注册微信应用");
                return;
            }
            
            if (!api.isWXAppInstalled()) {
                promise.reject("NOT_INSTALLED", "未安装微信");
                return;
            }
            
            payPromise = promise;
            
            PayReq req = new PayReq();
            req.appId = payload.getString("appId");
            req.partnerId = payload.getString("partnerId");
            req.prepayId = payload.getString("prepayId");
            req.nonceStr = payload.getString("nonceStr");
            req.timeStamp = payload.getString("timeStamp");
            req.packageValue = "Sign=WXPay";
            req.sign = payload.getString("sign");
            
            api.sendReq(req);
        } catch (Exception e) {
            promise.reject("PAY_ERROR", e.getMessage());
        }
    }
    
    /**
     * 检查微信是否已安装
     * @param promise Promise回调
     */
    @ReactMethod
    public void isWXAppInstalled(Promise promise) {
        try {
            if (api == null) {
                promise.resolve(false);
                return;
            }
            
            promise.resolve(api.isWXAppInstalled());
        } catch (Exception e) {
            promise.reject("CHECK_ERROR", e.getMessage());
        }
    }
}